package com.aaa.system.service.impl;

import com.aaa.entity.RoleUser;
import com.aaa.entity.User;
import com.aaa.system.dao.RoleDao;
import com.aaa.system.dao.UserDao;
import com.aaa.system.service.RoleService;
import com.aaa.system.service.UserService;
import com.aaa.system.vo.RoleVo;
import com.aaa.utils.JWTUtils;
import com.aaa.utils.WebUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.aaa.entity.Role;
import com.aaa.vo.Result;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @author Lei
 * @create 2023-03-22 18:42
 */
@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleDao roleDao;

    @Resource
    private UserDao userDao;

    @Resource
    private UserService userService;

    @Override
    public Result<List<Role>> getAll() {
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status",0);
        List<Role> roles = roleDao.selectList(queryWrapper);
        return new Result<>(200,"查询所有角色成功",roles);
    }

    @Override
    public Result<Map<String,Object>> getByUserId(Long userId) {
        List<Role> userRoles = roleDao.getByUerId(userId);
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status",0);
        queryWrapper.eq("del_flag",0);
        List<Role> roles = roleDao.selectList(queryWrapper);
        //将全部角色和当前用户的角色放进同一个map中，在前端进行拿取
        Map<String,Object> map = new HashMap<>();
        map.put("roles",roles);
        map.put("userRoles",userRoles);
        return new Result<>(200,"查询用户角色成功",map);
    }

    //开启事务
    @Transactional
    @Override
    public Result<String> confirmRole(Long userId, Long[] roleIds) {
        // 先删除当前用户的角色信息
        roleDao.deleteRole(userId);
        // 然后添加当前用户的修改后的角色信息
        if (roleIds.length!=0){
            roleDao.batchInsert(userId,roleIds);
        }
        return new Result<>(200,"分配角色成功");
    }

    @Override
    public Result<IPage<Role>> getAllRole(Integer current, Integer size, RoleVo roleVo) {
        IPage<Role> roleIPage = new Page<>(current,size);
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        if (StringUtils.hasText(roleVo.getRoleName())){
            queryWrapper.like("role_name",roleVo.getRoleName());
        }
        if (StringUtils.hasText(roleVo.getRoleCode())){
            queryWrapper.like("role_code",roleVo.getRoleCode());
        }
        if (Objects.nonNull(roleVo.getStatus())){
            queryWrapper.eq("status",roleVo.getStatus());
        }
        if (Objects.nonNull(roleVo.getDateRange())&&roleVo.getDateRange().length==2){
            queryWrapper.between("create_time",roleVo.getDateRange()[0],roleVo.getDateRange()[1]);
        }
        queryWrapper.eq("del_flag","0");
        IPage<Role> roleIPage1 = roleDao.selectPage(roleIPage, queryWrapper);
        return new Result<>(200,"查询所有角色成功",roleIPage1);
    }

    @Override
    public Result<Boolean> saveOrUpdateRole(Role role) {

        //直接在token获取手机号
        HttpServletRequest request = WebUtil.getRequest();
        String token = request.getHeader("token");
        Map<String, Object> tokenInfo = JWTUtils.getInfo(token);
        String phone = tokenInfo.get("username").toString();
        //通过token获取登录用户信息
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone",phone);
        User userByToken = userDao.selectOne(queryWrapper);

        User user = userService.getUser();
        if (Objects.nonNull(role.getRoleId())){
            //如果拥有角色Id，那么就是修改角色信息
            role.setUpdateTime(new Date());
            role.setUpdateBy(userByToken.getUserName());
            int i = roleDao.updateById(role);
            return new Result<Boolean>(200,"修改角色信息成功",i>0?true:false);
        }else {
            role.setCreateTime(new Date());
            role.setCreateBy(userByToken.getUserName());
            int insert = roleDao.insert(role);
            return new Result<Boolean>(200,"添加角色信息成功",insert>0?true:false);
        }
    }

    @Transactional
    @Override
    public Result<Long[]> delRole(Long roleId) {
        //不可以删除的角色
        Long[] noList = new Long[1];
        //判断是否有用户拥有当前角色，如果有，则不能删除当前角色
        List<RoleUser> roleUsers = userDao.selectUserById(roleId);
        if (roleUsers.size()>0){
            noList[0]=roleId;
            return new Result<Long[]>(200,"删除失败",noList);
        }else {
            //删除当前角色
            roleDao.deleteById(roleId);
            //删除该角色拥有的菜单数据，不删除菜单
            roleDao.delRoleMenu(roleId);
            return new Result<Long[]>(200,"删除成功");
        }
    }

    @Override
    public Result<ArrayList<Long>> mulDelRole(Long[] roleIds) {
        //循环遍历角色id，如果有用户拥有该角色，该角色不能删除

        //可以删除的角色
        ArrayList<Long> okList = new ArrayList<>();

        //不可以删除的角色
        ArrayList<Long> noList = new ArrayList<>();
        String msg = "";
        for (Long roleId : roleIds) {
            List<RoleUser> roleUsers = roleDao.selectUserById(roleId);
            if (roleUsers.size()>0){
                //如果有用户拥有当前角色，则不能进行删除
                noList.add(roleId);
                msg="批量删除失败";
            }else {
                okList.add(roleId);
                msg="批量删除成功";
            }
        }
        if (noList.size() == 0){
            boolean b = roleDao.batchDelRole(okList);
        }
        return new Result<ArrayList<Long>>(200,msg,noList);
    }
}
